package com.palm.app.tippix.sambaprenabler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;

import org.json.JSONException;
import org.json.JSONObject;

import com.palm.luna.LSException;
import com.palm.luna.message.ErrorMessage;
import com.palm.luna.service.LunaServiceThread;
import com.palm.luna.service.ServiceMessage;

public class SambaPREnablerEngine extends LunaServiceThread {
	
    private String name = "SambaPREnabler";
    private String version = "0.0.2";
    
	@LunaServiceThread.PublicMethod
	public void enable(ServiceMessage msg) throws InterruptedException, JSONException, LSException, IOException
	{ 
		try
		{
			if (msg.getJSONPayload().has("enabled")) 
			{
				boolean enabledParam = msg.getJSONPayload().getBoolean("enabled");

				Process p;
				
				if (enabledParam) {
					p = Runtime.getRuntime().exec("/opt/sbin/samba_start.sh");
				}
				else {
					p = Runtime.getRuntime().exec("/opt/sbin/samba_stop.sh"); 
				}

				BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
				String line = null; 
				String output = ""; 
				while ((line = input.readLine()) != null) { 
					output = output + line; 
				} 
				input.close();
				JSONObject reply = new JSONObject(); 
				reply.put("result", output); 
				msg.respond(reply.toString());
				p.waitFor();

			}
			else 
			{
			    msg.respondError(ErrorMessage.ERROR_CODE_INVALID_PARAMETER, "Missing 'enabled' parameter");
			}
		}
		catch (LSException e) 
		{
			this.logger.severe("", e);
		}
	}
	
	@LunaServiceThread.PublicMethod
	public void isRunning(ServiceMessage msg) throws InterruptedException, JSONException, LSException, IOException
	{ 
		try
		{
			Process p;
			
			p = Runtime.getRuntime().exec("/opt/sbin/samba_status.sh"); 

			BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = null;
			String output = "";
			while ((line = input.readLine()) != null) { 
				output = output + line; 
			} 
			input.close();
			JSONObject reply = new JSONObject(); 
			reply.put("result", output); 
			msg.respond(reply.toString());
			p.waitFor();

		}
		catch (LSException e) 
		{
			this.logger.severe("", e);
		}
	}
	
	@LunaServiceThread.PublicMethod
	public void createUser(ServiceMessage msg) throws InterruptedException, JSONException, LSException, IOException
	{ 
		try
		{
			Process p;
			
			p = Runtime.getRuntime().exec("/bin/echo -n -e \"passwort\npasswort\n\" | /opt/bin/smbpasswd -a benutzer -s"); 

			BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = null;
			String output = "";
			while ((line = input.readLine()) != null) { 
				output = output + line; 
			} 
			input.close();
			JSONObject reply = new JSONObject(); 
			reply.put("result", output); 
			msg.respond(reply.toString());
			p.waitFor();

		}
		catch (LSException e) 
		{
			this.logger.severe("", e);
		}
	}
	
	@LunaServiceThread.PublicMethod
	public void createConfig(ServiceMessage msg) throws InterruptedException, JSONException, LSException, IOException
	{ 
		try
		{
			if (msg.getJSONPayload().has("workgroup") &&
					msg.getJSONPayload().has("serverstring") &&
					msg.getJSONPayload().has("user")) {
				boolean success = true;

				Writer fw = null;
				
				String workgroupParam = msg.getJSONPayload().getString("workgroup");
				String serverstringParam = msg.getJSONPayload().getString("serverstring");
				String userParam = msg.getJSONPayload().getString("user");
				
				String finalConfig = config.replace("$WORKGROUP$", workgroupParam);
				finalConfig = finalConfig.replace("$SERVERSTRING$", serverstringParam);
				finalConfig = finalConfig.replace("$NETBIOSNAME$", serverstringParam.toLowerCase().replace(' ', '_'));
				finalConfig = finalConfig.replace("$ADMINUSER$", userParam);

				try {
					File dir = new File("/opt/etc/samba/");
					dir.mkdirs();
					
					fw = new FileWriter("/opt/etc/samba/smb.conf");

					fw.write(finalConfig);

				} catch (IOException e) {
					success = false;
					this.logger.severe("Could not create config file.");
				} finally {
					if (fw != null)
						try {
							fw.close();
						} catch (IOException e) {
							success = false;
						}
				}

				JSONObject reply = new JSONObject();
				reply.put("result", success);
				msg.respond(reply.toString());

			}
			else {
			    msg.respondError(ErrorMessage.ERROR_CODE_INVALID_PARAMETER, "Missing parameter");
			}
		}
		catch (LSException e) {
			this.logger.severe("", e);
		}
	}
    
    
	@LunaServiceThread.PublicMethod
	public void version(ServiceMessage msg) throws JSONException, LSException
	{
		try
		{
			JSONObject reply = new JSONObject(); 
			reply.put("name", this.name); 
			reply.put("version", this.version); 
			msg.respond(reply.toString());
		}
		catch (LSException e) 
		{
			this.logger.severe("", e);
		}
	}
	
	@LunaServiceThread.PublicMethod
	public void status(ServiceMessage msg) throws JSONException, LSException
	{
		try
		{
			JSONObject reply = new JSONObject();
			reply.put("returnValue",true);
			msg.respond(reply.toString());
		}
		catch (LSException e) 
		{
			this.logger.severe("", e);
		}
	}

	
	private String config = "[global]\n" +
			"workgroup = $WORKGROUP$\n" +
			"server string = $SERVERSTRING$\n" +
			"netbios name = $NETBIOSNAME$\n" +
			"load printers = no\n" +
			"log file = /var/log/samba.%m\n" +
			"max log size = 10\n" +
			"interfaces = eth0 lo\n" +
			"bind interfaces only = yes\n" +
			"debug level = 3\n" +
			"security = user\n" +
			"smb passwd file = /opt/etc/samba/smbpasswd\n" +
			"encrypt passwords = yes\n" +
			"guest account = nobody\n" +
			"config file = /opt/etc/samba/smb.conf\n" +
			"domain master = no\n" +
			"local master = no\n" +
			"prefered master = no\n" +
			"domain logons = no\n" +
			"wins support = no\n" +
			"wins proxy = no\n" +
			"dns proxy = no\n" +
			"admin users = root, $ADMINUSER$\n" +
			"[internal]\n" +
			"comment = Internal\n" +
			"path = /media/internal\n" +
			"public = yes\n" +
			"writable = yes\n";
}
